/**
 * Created by virgil on 15-9-29.
 */
/*var host="http://192.168.0.156:8080/web";
var wsHost="ws://192.168.0.156:8080/web";*/
//document.domain="192.168.0.156";

//var host="http://192.168.0.124:8080/web";
//var wsHost="ws://192.168.0.124:8080/web";


//var host="/web/api";
//var wsHost='https:'==document.location.protocol?"wss://"+document.location.host+"/web"s:"ws://"+document.location.host+"/web";

//cors
var loginPageUrl="/HNFrontToEnd/login.html";
var hostIP="192.168.0.123:9090";
var host=document.location.protocol+"//"+hostIP+"/web/api";
var wsHost='https:'==document.location.protocol?"wss://"+hostIP+"/web":"ws://"+hostIP+"/web";
var hostTest=document.location.protocol+"//192.168.0.249:8080/web/api";


/*var docUrl=host+"/doc/orderEfficiencyStatistics.html";*/
var m={
    "tCollectTime":"T_COLLECT_TIME",
    "cCreateTime":"C_CREATE_TIME",
    "cUpdateTime":"C_UPDATE_TIME"
};
//上次弹窗发生时间
var lastAlertTime=0;
//上次弹窗内容
var lastAlertContent="";
//同样内容弹窗最少间隔
var MIN_ALERT_TIME_INTERVAL=3000;

var pageSize_init_20=20;

Array.prototype.indexOf=function(val){
    for(var i=0;i<this.length;i++){
        if(this[i]==val)return i;
    }
    return -1;
};

Array.prototype.remove=function(val){
    var index=this.indexOf(val);
    if(index==-1){

    }else{
        this.splice(index,1)

    }
};

function cleanWindowInputValue(window){
    var inputs= $(window).find("input");

    for(var i=0;i<inputs.length;i++){

        var input=inputs[i];

        var inputType=$(input).attr("type");
        // console.log(inputType);

        if(inputType=="text" || inputType=="password")
        {
            $(input).val("");
        }

    }

}

function closeWindow(window){

  //  cleanWindowInputValue(window);
    window.window("close");


}
function openWindow(window){

    cleanWindowInputValue(window);
    window.window('center');
    window.window("open");


}

var common={
     pageParameter:{

        pageSize: pageSize_init_20,//每页显示的记录条数，默认为5
        pageList: [5, 10, 20, 25],//可以设置每页记录条数的列表
        beforePageText: '第',//页数文本框前显示的汉字
        afterPageText: '页    共 {pages} 页',
        displayMsg: '当前显示 {from} - {to} 条记录   共 {total} 条记录'
    },

    realPlayError:[
        {value:"-1",desc:"参数错误!"},
        {value:"0",desc:"取流成功!"},
        {value:"1",desc:"初始化失败!"},
        {value:"2",desc:"登录设备失败!"},
        {value:"3",desc:"打开实时流失败!"},
        {value:"4",desc:"设置实时流数据回调失败!"}
    ],


    //createImageUrl:function(cameraCode,collectTime){
    //    var d=new Date(collectTime);
    //    //20_2016-01-06_17-02-59.jpg
    //    var url=imageHost+"/"+cameraCode+"_";
    //    var month= d.getMonth()+1;
    //    var day= d.getDate();
    //    var hour= d.getHours();
    //    var minute= d.getMinutes();
    //    var second= d.getSeconds();
    //    var timeStr= d.getFullYear()+"-"
    //        + (month<10?"0"+month:month)+"-"
    //        + (day<10?"0"+day:day)+"_"
    //        + (hour<10?"0"+hour:hour)+"-"
    //        + (minute<10?"0"+minute:minute)+"-"
    //        + (second<10?"0"+second:second)+".jpg";
    //    return url+timeStr;
    //},

    createImageUrl:function(cameraCode,collectTime){

        var d=new Date(collectTime);

        //20_2016-01-06_17-02-59.jpg
        //var url=imageHost+"/"+cameraCode+"_";
        var url=host+"/fileService/download?fileName="+""+cameraCode+"_";
        var month= d.getMonth()+1;
        var day= d.getDate();
        var hour= d.getHours();
        var minute= d.getMinutes();
        var second= d.getSeconds();
        var timeStr= d.getFullYear()+"-"
            + (month<10?"0"+month:month)+"-"
            + (day<10?"0"+day:day)+" "
            + (hour<10?"0"+hour:hour)+"-"
            + (minute<10?"0"+minute:minute)+"-"
            + (second<10?"0"+second:second)+".jpg";
        return url+timeStr;
    },

    loadTableData:function(data,tableId){
        var tableIdStr="#"+tableId;
        if(data.result){
            var wellFormData={
                total:data.extra,
                rows:data.data
            };
            $(tableIdStr).datagrid("loadData",wellFormData);
            if($(".datagrid-mask")){
                $(".datagrid-mask").remove();
            }
            if($(".datagrid-mask-msg")){
                $(".datagrid-mask-msg").remove();
            }
        }else{
            //$(tableIdStr).datagrid("loadData",{total:0,rows:[]});
            $(tableIdStr).datagrid("loadData",[]);
            layer.confirm(data.description,{icon:-1,title:"提示",end:function(){}});

        }


    },

    //clearTableData:function(tableId){
    //    var clearedData=[];
    //    var tableIdStr="#"+tableId;
    //    $(tableIdStr).datagrid("loadData",{total:0,rows:[]});
    //},

    loadTableData_withoutTotal:function(data,tableId){
        var tableIdStr="#"+tableId;
        if(data.result){
            var wellFormData={
                rows:data.data
            };
            $(tableIdStr).datagrid("loadData",wellFormData);
            if($(".datagrid-mask")){
                $(".datagrid-mask").remove();
            }
            if($(".datagrid-mask-msg")){
                $(".datagrid-mask-msg").remove();
            }
        }else{
            $(tableIdStr).datagrid("loadData",{total:0,rows:[]});
        }


    },
    //毫秒转换成年月日 时分秒  以"年"、“月”、“日”衔接
    dateFormatter:function(value,rec,index){

        if(value!=undefined){

            var value1=Number(value);
            var d=new Date(value1);
            var year= d.getFullYear();
            var month= d.getMonth()+1;
            var day= d.getDate();
            var hour= d.getHours();
            var minute= d.getMinutes();
            var second= d.getSeconds();
            var timeStr=year+"年"+(month<10?"0"+month:month)+"月"+(day<10?"0"+day:day)+"日 "+(hour<10?"0"+hour:hour)+":"+(minute<10?"0"+minute:minute)+":"+(second<10?"0"+second:second);
            return  timeStr;


           // return unixTimestamp.toLocaleString();
        }
        return value;
    },
    //毫秒转换成年月日 时分秒  以连词符-衔接
    dateFormatter_hyphen:function(value,rec,index){

        if(value!=undefined){

            var value1=Number(value);
            var d=new Date(value1);
            var year= d.getFullYear();
            var month= d.getMonth()+1;
            var day= d.getDate();
            var hour= d.getHours();
            var minute= d.getMinutes();
            var second= d.getSeconds();
            var timeStr=year+"-"+(month<10?"0"+month:month)+"-"+(day<10?"0"+day:day)+" "+(hour<10?"0"+hour:hour)+":"+(minute<10?"0"+minute:minute)+":"+(second<10?"0"+second:second);
            return  timeStr;

            // return unixTimestamp.toLocaleString();
        }
        return value;
    },
    //截止到天
    dateFormatter_hyphen_day:function(value,rec,index){

        if(value!=undefined){

            var value1=Number(value);
            var d=new Date(value1);
            var year= d.getFullYear();
            var month= d.getMonth()+1;
            var day= d.getDate();
            //var hour= d.getHours();
            //var minute= d.getMinutes();
            //var second= d.getSeconds();
            var timeStr=year+"-"+(month<10?"0"+month:month)+"-"+(day<10?"0"+day:day);
            return  timeStr;

            // return unixTimestamp.toLocaleString();
        }
        return value;
    },
    //时间只取时分秒。
    dateFormatter_hms:function(value,rec,index){

        if(value!=undefined){

            var value1=Number(value);
            var d=new Date(value1);
            var hour= d.getHours();
            var minute= d.getMinutes();
            var second= d.getSeconds();
            var timeStr=(hour<10?"0"+hour:hour)+":"+(minute<10?"0"+minute:minute)+":"+(second<10?"0"+second:second);
            return  timeStr;


            // return unixTimestamp.toLocaleString();
        }
        return value;
    },

    //时间只取年月日
    dateFormatter_yyd:function(value,rec,index){

        if(value!=undefined){

            var value1=Number(value);
            var d=new Date(value1);
            var year= d.getFullYear();
            var month= d.getMonth()+1;
            var day= d.getDate();
            var timeStr=year+"-"+(month<10?"0"+month:month)+"-"+(day<10?"0"+day:day)+"-";
            return  timeStr;


            // return unixTimestamp.toLocaleString();
        }
        return value;
    },
    //年月日时分秒转换成 毫秒
    dateFormatter_inverse:function(value,rec,index){

        if(value!=undefined){

            var dateTimeMilliSecond=Date.parse(value);
            if(isNaN(dateTimeMilliSecond)){
                var new_dateTimeMilliSecond=value.replace('-','/');
                new_dateTimeMilliSecond=new_dateTimeMilliSecond.replace('年','/');
                new_dateTimeMilliSecond=new_dateTimeMilliSecond.replace('月','/');
                new_dateTimeMilliSecond=new_dateTimeMilliSecond.replace('日','/');
                return (new Date(new_dateTimeMilliSecond)).getTime();

            }else{
                return dateTimeMilliSecond
            }

        }
        return value;
    },

    //去除时分秒：只保留日期（时分秒阶段为00:00:00）
    dateFormatter_noHMS:function(value,rec,index){
        var newCurrent=value.substr(0,11)+"00:00:00";
        return newCurrent
    },
    //修复easyui datebox:修复前datebox数据转换为时分秒默认为上午八点，修复后改为00:00:00
    dateFormatter_fixTime:function(value){
        return new Date(value).getTime()-60*60*8*1000
    },
    getCurrentTime:function(){

        var obj=new Date();

        return obj.getTime();

    },
    vqdResultFormatter:function(value,rec,index){

        switch (value) {
            case 0: return "成功";
            case 1: return "设备离线";
            case 2: return "设备离线";
            case 3: return "登录设备失败";
            case 4: return "取流异常";
            case 5: return "取流异常";
            case 6: return "取流异常";
            default: return undefined;

            //case 0: return "成功";
            //case 1: return "创建线程失败";
            //case 2: return "设备SDK初始化异常";
            //case 3: return "登录设备失败";
            //case 4: return "预览设备视频失败";
            //case 5: return "回调视频流失败";
            //case 6: return "取流超时";
            //default: return undefined;
        }


    },
    serviceWorkStatusFormatter:function(value,rec,index){
      switch(value){
          case 0: return "正常";
          case 1: return "高负荷";
          case 2: return "损坏";
          case 3: return "离线";
          case 4: return "长时间静默";
          default: return undefined;

      }
    },


    //异常原因转义函数
    alarmCause:function(value,row,index){
        cause=row.cAlarmCause;
        var str="设备不在线";
        if(cause=="0"){
            return str;
        }
    },

    //异常来源钻转义函数
    alarmSrcFormatter:function(value,rec,index){
        switch(value){
            case 1: return "视频质量诊断";
            case 2: return "录像质量诊断";
            case 3: return "设备在线";
            case 4: return "服务在线";
            default: return undefined;

        }
    },

    //工单状态转义函数
    orderStatusFormatter:function(value,rec,index){

        switch(value){
            case 0: return "已上报";
            case 1: return "已确认";
            case 2: return "已挂起";
            case 3: return "已申请延期";
            case 4: return "已反馈";
            case 5: return "已结束";
            case 6: return "已驳回";
            default: return undefined;

        }
    },
    orgCodeToOrgNameFormatter:function(value,row,index){
        var cOrgName=orgCodeToOrgName(value);
        return cOrgName
    },

    /*返回一个UserInfo对象*/
    getUserInfo:function(){

        var userInfoStr=this.getCookieByKey("userInfo");

        try{

            var userInfo=JSON.parse(userInfoStr);
            return userInfo;
        }catch (e){

            return null;
        }

        return null;


    },

    //getRepairFeedBackImgFromId:function(value,row,index){
    //    var cid = value;
    //    var value = "";
    //    var imgArr = [];
    //    fileService.getWorkOrderFeedbackPicture(cid,function(data){
    //        if(data.result){
    //            var  imgs = data.data;
    //            //console.log(imgs);
    //            var imgArr = ["FD_image1","FD_image2","FD_image3"];
    //            for(var i=0;i<data.dataCount;i++)
    //            {
    //                var img = imgs[i];
    //                console.log(img);
    //                var imgUrl = host+"/fileService/downloadWorkOrderFeedbackPicture?cWdId="+cid+"&fileName="+img;
    //                var minUrl = imgUrl+"&width=50&height=50";
    //                //var str = "<img style=\"height: 50px;width: 50px;\" src=\""+imgUrl+"\"/>";
    //                var str='<img style=\"height: 50px;width: 50px;margin-left:10px\" layer-pid="'+img+'" layer-src="'+imgUrl+'" src="'+minUrl+'" alt="图片'+(i+1)+'">';
    //                imgArr[i]=str;
    //                //window.open(imgUrl);
    //            }
    //            value='<div onclick="showPicture(\''+cid+'\')" id="layer-photos-demo-'+cid+'" class="layer-photos-demo" style="height: 50px;padding:5px;">';
    //            for( var i=0;i<data.dataCount;i++){
    //                value+=imgArr[i];
    //            }
    //            value+='</div>';
    //            setTimeout('showPicture("'+cid+'")',500);
    //            var target = document.getElementById('test');
    //            target.innerHTML= value;
    //        }else{
    //            layer.confirm(data.description, {icon: -1, title: "提示", end: function () {}});
    //        }
    //    });
    //    //var reaader = new FileReader();
    //    //reaader.readAsDataURL(value);
    //
    //    return value;
    //},

    getRecordImgFromId:function (value,row,index) {
        var cid = value;
        var repairService = repair();
        var value = "";
        var imgArr = ["pic1","pic2","pic3"];
        //通过cid查找到上传的图片
        $.ajax({
            url:host+"/repair/record/picture/list",
            type:'get',
            async:false,
            data:{
                cRecordId:cid,
            },
            cache:false,
            error:common.onError,
            success:function (data) {
                if(data.result)
                {
                    var imgs = data.data;
                    //console.log(imgs);

                    for(var i=0;i<data.dataCount;i++)
                    {
                        var img = imgs[i];
                        //console.log(img);
                        var originImageUrl=host+"/repair/record/picture/download?cRecordId="+cid+"&fileName="+img;
                        var thumbnailImageUrl = originImageUrl+"&width=50&height=50";
                       // var str = "<img style=\"height: 50px;width: 50px;\" src=\""+imgUrl+"\"/>";
                        var str='<img oncontextmenu="deletePicture(event,\''+cid+'\',\''+img+'\')" layer-pid="'+img+'" layer-src="'+originImageUrl+'" src="'+thumbnailImageUrl+'" alt="图片'+(i+1)+'" width="50px" height="50px" style="margin-left:5px;">';
                        imgArr[i]=str;
                    }
                    value='<div oncontextmenu="addPicture(event,\''+cid+'\')" onclick="showPicture(\''+cid+'\')" id="layer-photos-demo-'+cid+'" class="layer-photos-demo" style="height: 50px;padding:5px;">';

                    for(var i=0;i<data.dataCount;i++){
                        value+=imgArr[i];
                    }
                    value+='</div>';
                    //console.log("第一次输出"+value);
                    setTimeout('showPicture("'+cid+'")',50);

                }
                else
                {
                    layer.confirm(data.description, {icon: -1, title: "提示", end: function () {}});
                }
            }
        });
        //console.log("第二次输出"+value);
        return value;

        //
        // repairService.getRepirRecordPictureList(cid,function (data) {
        //     if(data.result)
        //     {
        //         var imgs = data.data;
        //         //console.log(imgs);
        //
        //         for(var i=0;i<data.dataCount;i++)
        //         {
        //             var img = imgs[i];
        //             //console.log(img);
        //             var imgUrl = host+"/repair/record/picture/download?cRecordId="+cid+"&fileName="+img;
        //             var str = "<img style=\"height: 50px;width: 50px;\" src=\""+imgUrl+"\"/>";
        //             imgArr[i]=str;
        //         }
        //         for(var i=0;i<data.dataCount;i++){
        //             value+=imgArr[i];
        //         }
        //         //console.log(value);
        //     }
        //     else
        //     {
        //         layer.confirm(data.description, {icon: -1, title: "提示", end: function () {}});
        //     }
        //
        // })
        // //再次拼接生成图片
        // console.log(value);


    },

    getRecordImgFromIdTest:function (value,row,index){
      return value+"xxx";
    },



    getCookieByKey:function(key){

        var strCookie=document.cookie;

       var reg=new RegExp("(^|)"+key+"=([^;]*)(;|$)");
        var value;
        if(value=document.cookie.match(reg)){

            return value[2];
        }else{

            return null;
        }

    },
    deleteCookieByKey:function(key){

        var date=new Date();
        date.setTime(date.getTime()-1000);
        document.cookie=key+"=a;expires="+date.toGMTString();
    },

    orderStrToBool:function(order){

        if(order=="asc"){

           return false;
        }else{

          return true;
        }
    },
    serverStatusFormatter:function(value,rec,index){

        switch (value){
            case 0:
                return "正常";
            case 1:
                return "高负荷";
            case 2:
                return "损坏";
            case 3:
                return "离线";
            case 4:
                return "长时间静默";


            default :
                return "未知";
        }
    },
    deviceStatusFormatter:function(value,rec,index){
        if(value==1){
            return "<span style='width:20px;'>在线</span>"
        }else if(value==3){
            return "<sapn>离线</sapn>"
        }else{
            return "<span>未知</span>"
        }
    },
    serverTypeFormatter:function(value,rec,index){
        //var valueType=parseInt(value.substring(10,13));
        var valueType=value;
        switch (valueType){

            case 213:
                return "运维业务服务器";
            case 214:
                return "网管服务器";
            case 215:
                return "媒体接入服务器";
            case 200:
                return "中心信令控制服务器";
            case 201:
                return "Web应用服务器";
            case 202:
                return "媒体分发服务器";
            case 203:
                return "代理服务器";
            case 204:
                return "安全服务器";
            case 205:
                return "报警服务器";
            case 206:
                return "数据库服务器";
            case 207:
                return "GIS服务器";
            case 208:
                return "管理服务器";
            case 209:
                return "接入网关";
            case 210:
                return "媒体存储服务器";
            case 211:
                return "信令安全路由网关";
            case 212:
                return "视频质量诊断服务器";
            case 216:
                return "报警服务器";
            case 217:
                return "Oracle数据库服务器";
            case 218:
                return "PostgreSQL数据库服务器";
            default :
                return "未知";
        }

    },
    iPtzStatusFormatter:function(value,row,index){
        var str="";
        if(value==0){
            str="<span class='Set_no'>否</span>"
        }else if(value==1){
            str="<span class='Set_yes'>是</span>"
        }else{
            str="未知"
        }
        return str
    },
    createMenuItem:function(id,text,iconCls,state,loadChild,action){

        var menuItem=
            {

                "id":id,
                "text":text,
                "iconCls":iconCls,
                "state":state,
                "attributes":{
                    loadChild:loadChild,
                    action:action
                }
            };

        return menuItem;

    },
    toLoginPage:function(msg){

        $.messager.confirm({
            title:'提示',
            msg:msg,
            fn:function(isConfirmed){

                //window.parent.location.href="/web/login.html";

                //cors
                window.parent.location.href=loginPageUrl

            }

        })

    },

    onVideoError: function (data) {
        try{

            var resp=data.responseText;

            var msg=JSON.parse(resp);
            var httpStatus=data.status;
            if(httpStatus==403){


                common.toLoginPage("你还没有登录,请重新登录");

            }else if(httpStatus==404){

                common.alert("视频客户端未打开，请打开或点击下载中心安装视频客户端！");
                //  window.parent.location.href="/web/login.html";
            }
        }catch(e){

            common.alert("视频客户端未打开，请打开或点击下载中心安装视频客户端！");
            console.log(data.responseText);
        }finally{

        }
    },

    onError:function(data){

        try{

            var resp=data.responseText;

            var msg=JSON.parse(resp);
            var httpStatus=data.status;
            if(httpStatus==403){


                common.toLoginPage("你还没有登录,请重新登录");

            }else if(httpStatus==404){

                common.alert("网络异常，请稍后再试");
              //  window.parent.location.href="/web/login.html";
            }
        }catch(e){

            common.alert("网络异常，请稍后再试");
            //alert("网络异常，请稍后再试");
         //   window.parent.location.href="/web/login.html";
                console.log(data.responseText);
        }finally{

        }




    },
    alert:function(msg,title){

        var currentTime=this.getCurrentTime();
        if(lastAlertContent==msg){

            if((currentTime-lastAlertContent)<MIN_ALERT_TIME_INTERVAL){

                return ;
            }

        }
        if(layer){
            layer.msg(msg);
        }
        lastAlertContent=currentTime;
        lastAlertContent=msg;
        $('#message').html(msg);
        //openWindow($('#myWindow'));
        //if($('#myModal_logout')){
        //    $('#myModal_logout').modal('show');
        //}


        //$.messager.alert({
        //
        //    title:title==undefined?"提示":title,
        //    msg:msg
        //})

    },

    loadPage:function(url,onSuccess){

        $.ajax({
            url:url,
            type:"get",
            cache:false,
            success:onSuccess,
            error:this.OnError
        })

    },
    planTemplateTimeToBinary:function(arr){
        if (!arr) {
            return;
        }
        var arr_binary=new Array(7);
        for(var m=0;m<arr_binary.length;m++){
            arr_binary[m]="";
        }
        for(var i=0;i<arr.length;i++){

            //如果某一天为空值，则将其转换为48个0组成的字符串
            if(arr[i]==""){
                for(m=0;m<48;m++){
                    arr_binary[i]+="0";
                }
            }
            //若某一天不是空值，则将其作如下处理
            else{
                //先将数据重新排序

                var arr_split=arr[i].split(";");//时间段分割;
                //删除最后一个空元素
                arr_split=deleteLastNullEle(arr_split);
                arr[i]=sortArr(arr[i]);
                arr_split=arr[i];
                //arr_split=arr_split.sort();
                for(var j=0;j<arr_split.length;j++){
                    var arr_split_=arr_split[j].split(",");//每个时间段，起始、结束分割
                    //arr_split_=deleteLastNullEle(arr_split_);
                    var arr_split_start = parseInt(arr_split_[0]);
                    var arr_split_end   = parseInt(arr_split_[1]);

                    //获取当前时间段的下一个时间段起始时间
                    var arr_next_split_;
                    var arr_next_split_start;
                    if((j+1)<arr_split.length){
                        arr_next_split_=arr_split[j+1].split(",");
                        arr_next_split_start=parseInt(arr_next_split_[0]);//每个时间段，起始、结束分割
                    }else{
                        arr_next_split_start=false
                    }

                    //if(arr_split.length==1){
                    //    arr_next_split_start=false
                    //}


                    var intervalNum;
                    var zero_num;
                    //如果是第一项，则进行如下操作
                    if(j==0){
                        //第一项的起始时间为0
                        if(arr_split_start==0){
                            //获得第一段时间有多少个半小时，itervalNum
                            intervalNum=(arr_split_end+1)/60/30;
                            for(var k=0;k<intervalNum;k++){
                                arr_binary[i]+="1";
                            }
                            //如果下一个时间段的起点存在的话；
                            if(arr_next_split_start){
                                //如果前一个时间段和后一个时间段中间有空时间段
                                if((arr_split_end+1)!=arr_next_split_start){
                                    zero_num=(arr_next_split_start-(arr_split_end+1))/60/30;
                                    for(k=0;k<zero_num;k++){
                                        arr_binary[i]+="0";
                                    }
                                }
                            }
                            //如果下一个时间段不存在的话：
                            else{
                                //如果前一个时间段和23:59.60s有空时间段
                                if((arr_split_end+1)!=86400){
                                    zero_num=(86400-(arr_split_end+1))/60/30;
                                    for(k=0;k<zero_num;k++){
                                        arr_binary[i]+="0";
                                    }
                                }
                            }
                        }
                        //若起始时间不为0；补零
                        else{
                            intervalNum=(arr_split_start)/60/30;
                            for(k=0;k<intervalNum;k++){
                                arr_binary[i]+="0";
                            }
                            var time_binary_interval=(arr_split_end-arr_split_start+1)/30/60;
                            for(k=0;k<time_binary_interval;k++){
                                arr_binary[i]+="1";
                            }
                            //如果有下一个时间段
                            if(arr_next_split_start) {
                                if ((arr_split_end + 1) != arr_next_split_start) {
                                    zero_num = (arr_next_split_start - (arr_split_end + 1)) / 60 / 30;
                                    for (k = 0; k < zero_num ; k++) {
                                        arr_binary[i] += "0";
                                    }
                                }
                            }
                            //如果是最后一个时间段，
                            // 则将其结束时间和86400比较。看需要补多少个0
                            else{
                                intervalNum=(86400-(arr_split_end+1))/60/30;
                                for (k = 0; k < intervalNum; k++) {
                                    arr_binary[i] += "0";
                                }
                            }
                        }

                    }
                    //如果不是第一项，则进行下面的操作
                    else{
                        //首位时间段半小时个数
                        time_binary_interval=((arr_split_end+1)-arr_split_start)/30/60;
                        for(k=0;k<time_binary_interval;k++){
                            arr_binary[i]+="1";
                        }
                        //若有下个时间段
                        if(arr_next_split_start){
                            //如果前一个时间段和后一个时间段中间有空时间段
                            if((arr_split_end+1)!=arr_next_split_start){
                                zero_num=(arr_next_split_start-(arr_split_end+1))/60/30;
                                for(k=0;k<zero_num;k++){
                                    arr_binary[i]+="0";
                                }
                            }
                        }
                        //若没有下个时间段，则和24:00:00比较看还有几个半小时
                        else{
                            intervalNum=(86400-(arr_split_end+1))/60/30;
                            for (k = 0; k < intervalNum ; k++) {
                                arr_binary[i] += "0";
                            }
                        }


                    }
                }
            }

            if(i==1){
                console.log('周二'+arr[i]);
                console.log('周二'+arr_binary[i]);

            }
        }

        //删除数组中最后一项为空值的元素
        function deleteLastNullEle(arr){
            var arr_new=new Array();
            if(arr.length>1){
                if(arr[arr.length-1]==""){
                    for(var q=0;q<arr.length-1;q++){
                        arr_new[q]=arr[q]
                    }
                }
                return arr_new
            }else{
                return arr
            }

        }

        function sortArr(numArry){
            var arrStorage=numArry;
            var newArray=[];
            var startTime=[];
            var newStartTime=[];
            //var order=[];
            var items=arrStorage.split(";");//时间段分割
            items=deleteLastNullEle(items);
            for(var m=0;m<items.length;m++){
                //每个时间段，起始、结束分割
                var timeIntevalSplit=items[m].split(",");
                startTime.push(parseInt(timeIntevalSplit[0]));
            }
            console.log(startTime);

            startTime=sortNum(startTime);

            for(var m=0;m<items.length;m++){
                //每个时间段，起始、结束分割
                timeIntevalSplit=items[m].split(",");
                newStartTime.push(parseInt(timeIntevalSplit[0]));
            }

            var order=[];
            for(m=0;m<newStartTime.length;m++){
                for(var n=0;n<newStartTime.length;n++){
                    var num=-1;
                    if(newStartTime[m]==startTime[n]){
                        num=n;
                        break
                    }else{
                        num=-1;
                    }
                }
                if(num!=-1){
                    order.push(num);
                }
            }

            for(m=0;m<items.length;m++){
                var testNum;
                for(n=0;n<order.length;n++){
                    if(m==order[n]){
                        testNum=n;
                        break
                    }
                }
                newArray[m]=items[testNum]
            }

            return newArray;

        }


        function sortNum(array){
            return array.sort(sequence);
        }

        function sequence(a,b){
            if(a>b){
                return 1;
            }else if(a<b){
                return -1;
            }else{
                return 0;
            }
        }

        return arr_binary
    },
    loadingModalCreate:function(){
        $("body").append("<!-- loading -->" +
            "<div class='modal fade' id='loading' tabindex='-1' role='dialog' aria-labelledby='myModalLabel' data-backdrop='static'>" +
            "<div class='modal-dialog' role='document'>" +
            "<div class='modal-content'>" +
            "<div class='modal-header'>" +
            "<h4 class='modal-title' id='myModalLabel'>提示</h4>" +
            "</div>" +
            "<div id='loadingText' class='modal-body'>" +
            "<span class='glyphicon glyphicon-refresh' aria-hidden='true'>1</span>" +
            "处理中，请稍候。。。" +
            "</div>" +
            "</div>" +
            "</div>" +
            "</div>"
        );
    },
    bootstrapTableLoadingShow:function(tableId){
        $(tableId).bootstrapTable('showLoading')
    },
    bootstrapTableLoadingHide:function(tableId){
        //$("#loading").modal("hide");
        $(tableId).bootstrapTable('hideLoading')
    },
    datagridLoading:function(tableId){
        $(tableId).datagrid('loading')
    },
    datagridLoaded:function(tableId){
        $(tableId).datagrid('loaded')
    },
    //如果图片过大，处理图片大小。使用要求：传递id和大小要求。示例：autoImgSize('img1',1000)
    autoImgSize:function(img,size){
        if(!size){
            size=400;//设置默认最大值为400
        }
        var imgobj= document.getElementById(img); //获取对象
        imgobj.style.width = "auto";
        imgobj.style.height = "auto";  //释放图片本来的大小
        var imgwidth=imgobj.width;
        var imgheight=imgobj.height;
        if(imgwidth>imgheight){     //判断是width和height哪一个大。大的先处理。设置最大值size
            if(imgwidth>size){
                imgobj.style.width = size + "px";
            }
            imgheight=imgobj.height;
            if(imgheight>size){

                imgobj.style.height = size + "px";
            }
        }else{
            if(imgheight>size){
                imgobj.style.height = size + "px";
            }
            imgwidth=imgobj.width;
            if(imgwidth>size){
                imgobj.style.width = size + "px";
            }
        }
    },
    ImgSetSize:function(img,width,height){
        var imgobj= document.getElementById(img); //获取对象
        imgobj.style.width = width + "px";
        imgobj.style.height = height + "px";
        //imgobj.style.width = "auto";
        //imgobj.style.height = "auto";  //释放图片本来的大小
        //var imgwidth=imgobj.width;
        //var imgheight=imgobj.height;
        //if(imgwidth>imgheight){     //判断是width和height哪一个大。大的先处理。设置最大值size
        //    if(imgwidth>size){
        //        imgobj.style.width = size + "px";
        //    }
        //    imgheight=imgobj.height;
        //    if(imgheight>size){
        //
        //        imgobj.style.height = size + "px";
        //    }
        //}else{
        //    if(imgheight>size){
        //        imgobj.style.height = size + "px";
        //    }
        //    imgwidth=imgobj.width;
        //    if(imgwidth>size){
        //        imgobj.style.width = size + "px";
        //    }
        //}
    },
    //判断输入框是否符合验证规范
    checkInvalid:function(inputs){
        var invalid_results=new Array();
        for(var i=0;i<inputs.length;i++){
            invalid_results[i]=common.textboxCheckInvalid(inputs[i])
        }
        var valid=true;
        for(var i=0;i<invalid_results.length;i++){
            if(invalid_results[i]==true){
                valid=false;
                break
            }
        }
        return valid;
    },
    textboxCheckInvalid:function(input){
        var invalidStr="invalid";
        var className=input.siblings()[0].className;
        var result=common.isContains(className,invalidStr);
        return result;
    },
    isContains:function(str,subStr){
        return str.indexOf(subStr)>=0;
    },
    getResTypeFormCode:function(resCode){
        return resCode.substring(10,13);
    },

    progressFormatter:function(value,row,index){
        if(value){
            var processed_value=parseFloat(parseFloat(value).toFixed(2));
        }else{
            value=0;
            //value=Math.random()*100;
            processed_value=parseFloat(parseFloat(value).toFixed(2));
        }
        var addedClass;
        if(processed_value<=80){
            addedClass="normalCapacity";
        }else if(processed_value>80){
            addedClass="criticalCapacity";
        }

        var htmlStr='<div class="easyui-progressbar'+' '+addedClass+'" data-options="value:'+processed_value+'" style="width:100%;"></div> ';

        return htmlStr;
    },
    progressFormatter_multiply100:function(value,row,index){
        if(value){
            var processed_value=parseFloat((parseFloat(value)*100).toFixed(2));
        }else{
            value=0;
            //value=Math.random()*100;
            processed_value=parseFloat((parseFloat(value)*100).toFixed(2));
        }
        var addedClass;
        if(processed_value<=80){
            addedClass="normalCapacity";
        }else if(processed_value>80){
            addedClass="criticalCapacity";
        }

        var htmlStr='<div class="easyui-progressbar'+' '+addedClass+'" data-options="value:'+processed_value+'" style="width:100%;"></div> ';

        return htmlStr;
    },

    //当hover在一个domElement时创建一个ID=descDiv的提示框；
    createDiv:function(eleId){
        //首先创建div
        var descDiv = document.createElement('div');
        document.body.appendChild(descDiv);
        //获取输入框dom元素
        var text = document.getElementById(eleId);
        //计算div的确切位置
        var seatX = text.offsetLeft ;//横坐标
        var seatY = text.offsetTop + text.offsetHeight +3;//纵坐标
        //给div设置样式，比如大小、位置
        var cssStr = "z-index:9999999;width:400px;height:20px;height:auto;min-height:20px;background-color:red;color:white;border:1px solid black;position:absolute;left:"
            + seatX + 'px;top:' + seatY + 'px;';
        //将样式添加到div上，显示div
        descDiv.style.cssText = cssStr;
        descDiv.innerHTML = text.innerHTML;
        descDiv.id = 'descDiv';
        descDiv.style.display = 'block';
    },
    //当鼠标移出element是，删除div
     destroyDiv:function(){
        var element=document.getElementById("descDiv");
        element.parentNode.removeChild(element);
    },
    openVideoInFrame:function(frameId,src){
        if(frameId){
            if(src==""){
                //如果不传src，默认路径为：
                // 直连版
                $("#"+frameId).attr("src","../../../videoPreview/views/video_direct.html");
                // 媒体网关
                //$("#"+frameId).attr("src","../../../videoPreview/views/video_media.html")

            }else if(src=="hn_home"){
                $("#"+frameId).attr("src","../../videoPreview/views/video_direct.html");
                //$("#"+frameId).attr("src","../../videoPreview/views/video_media.html")


            }else{

            }

        }else{
            console.log("iframe的ID不存在！")
        }
    },
    createDivTooltip:function(ele){
//首先创建div
        var descDiv = document.createElement('div');
        document.body.appendChild(descDiv);
        //获取输入框dom元素
        var text = document.getElementById(ele.id);

        var w=text.clientWidth,h=text.clientHeight;
        //var w=text.offsetWidth,h=text.offsetHeight;
        for(var t=text.offsetTop,l=text.offsetLeft;text=text.offsetParent;){
            t+=text.offsetTop;
            l+=text.offsetLeft;
        }


        //计算div的确切位置
        var seatX = l-70+w/2;//横坐标--这里要根据 .tooltips 样式的宽和高定位
        var seatY = t+30;//纵坐标
        //给div设置样式，比如大小、位置
        var cssStr = "position:absolute;z-index:9999999;height:auto;min-height:20px;position:absolute;"+
            'left:'+ seatX + 'px;top:' + seatY + 'px;background-color:black;color:white;padding:5px 8px 5px 8px';
        //将样式添加到div上，显示div
        descDiv.style.cssText = cssStr;

        var content="告警列表展示（显示/隐藏）";

        //ele.style.border="0.5px solid black";

        descDiv.innerHTML = '<div class="tooltips" ><a style="color:white;text-decoration: none">'+content+'</a><div class="arrow"></div></div>';
        descDiv.id = 'descDiv';
        //descDiv.style.display = 'block';
        //descDiv.style.top = '300px';
        $(".tooltips").tooltips({

        })
    },
    destroyDivTooltip:function(ele){
        var element=document.getElementById("descDiv");
        if(element){
            element.parentNode.removeChild(element);
        }
    },
    resetPage:function(pageEntity,originalPage){

    },

    grantPagePermission:function(cRole,cUrl,service,onGet){
        if(service){
            try{
                service.getDeviceTypeList(function(data){
                    if(data.result){
                        if(data.data){
                            onGet(data.data);
                        }
                    }
                    else{
                        alert(data.description)
                    }
                });

                //service.getOperationPermissionByRoleIdAndUrl(cRole,cUrl,function(data){
                //    if(data.result){
                //        if(data.data){
                //            var temp=data.data;
                //            //若.operable属性为false,则隐藏页面中的增删改查按钮
                //            if(temp.operable&&!temp.operable){
                //                onGet(temp.operable);
                //            }
                //            else if(temp.operableState&&!temp.operableState){
                //                onGet(temp.operableState);
                //            }
                //            else{
                //                onGet("error,return value attribute error");
                //            }
                //        }
                //    }
                //    else{
                //        alert(data.description)
                //    }
                //})
            }
            catch(e){
                console.log(e)
            }
        }
        else{
            alert('权限接口未正确引用！')
        }
    }
};

//cors
$.ajaxSetup({

    crossDomain:true,xhrFields:{withCredentials:true},
    error:common.onError
})

/**
 *对Date的扩展，将 Date 转化为指定格式的String
 *月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
 *年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
 *例子：
 *(new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
 *(new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
 */
Date.prototype.format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}